package com.zl.common.config;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;

public class RoutingDatasource implements DataSource {
	//缓存多个datasource
	private Map<String, DataSource> datasources = new HashMap<String,DataSource>();
	
	//重写 getConnection 方法
	//businessFlag 就是业务标识信息，表示要连哪个数据库，可以放在ThreadLocal里面，每个线程不一样
	@Override
	public Connection getConnection() throws SQLException {
		String businessFlag = PlatformContext.getBusinessFlag();
		DataSource routingDataSource = datasources.get(businessFlag);
		if(routingDataSource == null) {
			synchronized (this) {
				routingDataSource = datasources.get(businessFlag);
				if(routingDataSource == null) {
					routingDataSource = createDatasource(businessFlag);
					datasources.put(businessFlag, routingDataSource);
				}
			}
		}
		return routingDataSource.getConnection();
	}
	
	//根据不同的业务标识创建DataSource
	//可以把不同数据库的连接信息放到数据库中，然后这个地方读取连接信息
	private  DataSource createDatasource(String businessFlag) {
		if(businessFlag == null){
			businessFlag = "test1";
		}
		String propertityname = "db_"+businessFlag+".properties";
		Prop dbProp = PropKit.use(propertityname);
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(dbProp.get("jdbcUrl"));// url
		dataSource.setUsername(dbProp.get("user")); // username
		dataSource.setPassword(dbProp.get("password")); // password
		return dataSource;
	}
	
	@Override
	public PrintWriter getLogWriter() throws SQLException {
        throw new UnsupportedOperationException("getLogWriter Not supported");
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
        throw new UnsupportedOperationException("setLogWriter Not supported");
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
        throw new UnsupportedOperationException("setLoginTimeout Not supported");

	}

	@Override
	public int getLoginTimeout() throws SQLException {
        throw new UnsupportedOperationException("getLoginTimeout Not supported");

	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new UnsupportedOperationException("getParentLogger Not supported");
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
        throw new UnsupportedOperationException("unwrap Not supported");
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
        throw new UnsupportedOperationException("isWrapperFor Not supported");
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {
        throw new UnsupportedOperationException("getConnection Not supported");
	}
}
